var ws, balance, aid, did, uid, vacu = '1', paytype='1',total,spage, price, ordernum;
var pays={};
var ptype = 'wxpay'; 
var w=null;
var url = '';
var sid , shop, rnums, address;//店铺名称、店铺所属商家Id、包装数量
document.addEventListener('plusready',function(){
	uid = plus.storage.getItem('uid');
	balance = plus.storage.getItem('money');
	ws = plus.webview.currentWebview();
	aid = ws.aid;
	did = ws.did;//医生id
	spage = ws.spage;
//	console.log(aid+" "+spage); 
	//支付方式
	$("input[name='radio2']").on('click',function(){
		paytype = $(this).attr('value');
		console.log(paytype);
		if(paytype == '1'){//线上支付
			$('.address-2-1').show('flast');
		}else{//线下支付
			$('.address-2-1').hide('flast');
		}
	})
	var dat = plus.storage.getItem('predata'); 
	var data = $.parseJSON(dat);
	$.each(data, function(k,v) {
		if(v.id == aid){
			plus.nativeUI.closeWaiting();
			console.log(JSON.stringify(v));
			$('.doctor').text(v.dinfo.name);
			if(v.wtype == 1){//图文咨询
				$('.wtype').text('图文咨询');
			}else if(v.wtype == 2){//电话咨询 
				$('.wtype').text('电话咨询');
			}else if(v.wtype == 3){//视频问诊
				$('.wtype').text('视频咨询');
			}
			$('.wtime').text(v.wtime);
			$('.ordernum').text(v.ordernum);
			total = v.total;
			$('.total').text(total);
			//线上线下取货
			switch(v.paytype){
				case '1' ://线上
					$('.quhuo').show();
					$('.address').text(v.shop);
					if(v.sinfo){
						$('.phone').text(v.sinfo.phone);
						$('.shopaddress').text(v.sinfo.address);
					}
					$('.downline').hide();
					$('.online').show();
				break;
				case '2' ://线下
					$('.quhuo').show();
					$('.address').text(v.shop);
					if(v.sinfo){
						$('.phone').text(v.sinfo.phone);
						$('.shopaddress').text(v.sinfo.address);
					}
					$('.online').hide();
					$('.downline').show();
				break;
			}
			//包装
			switch(v.recipetype){
				case '1' :
					$('.baozhuang').hide();
					$('.ztype').text('中药饮片');
				break;
				case '2' :
				$('.baozhuang').show();
					$('.ztype').text('中药汤药（真空包装）');
					$('.znum').text(v.recipenum+"副");
				break;
			}
			
			if(v.status == '0'){
				$('.rz-btn').text('立即提交');
				$('.waitPay').show();
				$('.orderprice').text(total);
				waipay();
			}else{
				$('.otherList').show();
				$('.orderprice').text(v.orderprice);
				$('.zhusu').val(v.history);
				if(v.status == '1'){
					$('.rz-btn').text('待接单');
				}else if(v.status == '2'){
					$('.rz-btn').text('确认收货');
				}else{
					$('.overOrder').hide();
				}
			}
			if(v.issee == 1){//可查看
				$('.online').show();
				$('.downline').hide();
			}
			if(v.recipe){
				var chu = v.recipe.split(';');
				var str1 = '', fang;
				$.each(chu, function(ko,vo) { 
					if(vo == ''){
						return true;
					}
					fang = vo.split(',');
					str1 += '<div class="mui-table-view table-view-cell bbs-ico font-15 color-ddd">'+
								'<li>'+
									'<span>'+fang[0]+'</span>'+
									'<span class="mui-pull-right">'+fang[1]+'</span>'+
								'</li>'+
							'</div>';
				});
				$('.caseList').html(str1);
			}
		}
	})
	// 获取支付通道
	plus.payment.getChannels(function(channels){
		for(var i in channels){
			var channel=channels[i];
			pays[channel.id]=channel;
			checkServices(channel);
		}
	},function(e){
		outLine("获取支付通道失败："+e.message);
	});
	//点击立即提交
	$('.overOrder').on('tap', function(){
		var rbtn = $('.rz-btn').text();//按钮
		price = $('.orderprice').text();//订单总额 
		ordernum = $('.ordernum').text();//订单号
		address = $('.bespoke-address').val();
		rnums = $('.mui-input-numbox').val();//包装数量
//		console.log(price+" "+ordernum);return; 
//		console.log(paytype);
		switch(rbtn){
			case '立即提交':
				if(vacu == '2' && rnums == 0){ 
					toast('请选择包装数量');return;
				}
				sid = $('.shopid').val();
				shop = $('#shop').text();
				if(!sid || !shop){
					toast('请选择店铺');return;
				}
				if(paytype == '1'){//线上支付
					if(!address.trim()){
						toast('请输入邮寄地址');return;
					}
					$('.zhifzzao').show();
    				$('.zhiftc').slideDown();
				}else{//线下支付
					downLine();
				}
			break;
			case '确认收货':
				//收货
				plus.nativeUI.confirm('请确认是否收到货，此操作不可逆',function(e){
					if(e.index == 0){
						$.ajax({
							type:"get",
							url:apiRoot+"?m=home&c=medicinal&a=updateStatus",
							data :{
								aid :aid,
								status :3
							},
							dataType :'json',
							success :function(data){
								console.log(JSON.stringify(data));
								if(data > 0){
									toast('操作成功');
									if(spage){
										plus.webview.getWebviewById(spage).reload();
									}
									setTimeout(function(){
										ws.close();
									},2000);
								}
							},
							error :function(e){
								console.log(JSON.stringify(e));
								errortoast();
							}
						});
					}
				},'确认收货','确认','取消');
			break;
		}
	})
	//选择店铺
	$('.changeshop').on('tap', function(){
		goNewPage('me-prescription-shop-list.html',{spage:ws.id});
	})
	//支付方式
	$('.zhiftc div').on('tap', function(){
		switch($(this).index()){
			case 1://点击微信支付
			toast('待接口提供');return;
			ptype = 'wxpay'; 
			payment();
			break;
			case 2://点击支付宝支付
			toast('待接口提供');return;
			ptype = 'alipay'; 
			payment();
			break;
			case 3://点击银联支付
			toast('待接口提供');return;
			break;
			case 4://点击余额支付
			console.log(price+ " "+balance);
			if(parseFloat(balance) < parseFloat(price)){
				toast('您的余额不足请及时充值');
			}else{
				ReBalance();
			}
			break;
		}
	})
	//关闭弹出框
	$('.cols').on('tap',function(){
    	$('.zhifzzao').fadeOut(500);
    	$('.zhiftc').slideUp();
    });
},false)
//减少账户余额
function ReBalance(){
	$.ajax({
		type:"get",
		url:apiRoot+"/home/income/Decbalance",
		data :{
			uid :uid,
			money :price
		},
		success:function(data){
			console.log(data);
			var str = parseFloat(balance) - parseFloat(price);
			plus.storage.setItem('money', str+'');
			paying();
		},
		error :function(e){
			console.log(JSON.stringify(e));
		}
	});
}
window.addEventListener('change',function(event){
	sid = event.detail.aid;
	shop = event.detail.title;
	console.log(sid+' '+shop);
	$('.shopid').val(sid);
	$('#shop').text(shop);
})
//线下支付	paytype:支付方式->1:线上支付，2:线下支付	vacu:包装方式->1:中药饮片，2:中药汤药
function downLine(){
//	console.log(ptotal +" "+shop+" "+paytype+" "+vacu+" "+rnums); return;
	showWating();
	paying();
}
//支付成功后保存信息修改状态
function paying(){
	console.log(shop+" "+paytype+" "+vacu); 
	$.ajax({
		type:"get",
		url:apiRoot+"?m=home&c=medicinal&a=savePro",
		data :{
			aid :aid,
			orderprice : price,
			shop : shop,//店铺名
			shopid : sid,//店铺所属商家id
			recipetype :vacu,//药物包装
			recipenum :rnums,//处方数量
			paytype :paytype,//线上/线下支付
			mailaddress :address,//邮寄地址
			status :1
		},
		dataType :'json',
		success :function(data){
			console.log(JSON.stringify(data));
			plus.nativeUI.closeWaiting();
			if(data > 0){
				source();
			}
		},
		error :function(e){
			console.log(JSON.stringify(e));
			errortoast();
		}
	});
}
//添加收入支出记录
function source(){
	var p = aid+'号订单记录';
	var money = parseFloat(total) * 0.2;
	var price = money.toFixed(2);
	console.log(p+" "+price);
	$.ajax({
		type:"get",
		url:apiRoot+"?m=home&c=income&a=recharge",
		data :{
			payer :uid,
			earner :did,
			source :p,
			money :price,
			tid :77//收入
		},
		dataType :'json',
		success :function(data){
			console.log(JSON.stringify(data));
			if(data > 0){
				if(spage){
					plus.webview.getWebviewById(spage).reload();
				}
				toast('提交成功');
				setTimeout(function(){
					ws.close();
				},2000);
			}
		},
		error :function(e){
			errortoast();
		}
	});
}
//支付
function payment(){
	console.log(ordernum+" "+price+" "+ptype);
	//预设订单Id ——> 用户Id+当前时间戳
	orderid = uid+new Date().getTime();
	if(w){return;}//检查是否请求订单中
	if(ptype == 'alipay'){
//		console.log(webRoot + '/pay/Alipay.php?orderid=' + ordernum + '&price='+price);return;
		url = webRoot + '/pay/Alipay.php?orderid=' + ordernum + '&price='+price;
	}else if(ptype == 'wxpay'){
//		console.log(webRoot + '/pay/index.php?orderid=' + orderid + '&price='+price);return;
		url = webRoot + '/pay/index.php?orderid=' + ordernum + '&price='+price+'&type=1';
	}
	w = plus.nativeUI.showWaiting('支付中...',{width:'80px',height:'80px',background:'rgba(0,0,0,0.3)'});
	// 请求支付订单
	var xhr=new XMLHttpRequest();
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		switch (xhr.readyState) {
			case 4:
			w.close(); 
			w = null;
			if (xhr.status == 200) { 
				var order = xhr.responseText;
				console.log(JSON.stringify(pays[ptype]));
				console.log(order);
				plus.payment.request(pays[ptype], order, function(result) { 
					//对订单进行操作
					paying();
				}, function(e) {
					console.log("提示", null, "支付失败");
					console.log("["+e.code+"]："+e.message);
				});
			} else { 
				plus.nativeUI.toast("获取订单信息失败！", null, "捐赠");
			}
			break;
		default:
			break;
		}
	}
	xhr.open('GET', url);
	xhr.send();
}
//等待付款
function waipay(){
	//药物包装切换
	$('input[name=radio1]').click(function(){
		vacu = $(this).attr('value');
//		console.log(vacu);
		if(vacu == '1'){
			$('.vacuumize').hide();
			$('.nums').hide();
			$('.mui-input-numbox').val(0);
			$('.orderprice').text($('.total').text());
		}else{
			$('.vacuumize').show();
			$('.nums').show(); 
		}
	})
	//mui +- 数量 失效 重写
	$(".mui-numbox button ").on('tap',function(){
		var bThis=$(this).parent();
		var bmin=parseInt(bThis.attr('data-numbox-min'));//设置最小值
		var bmax=parseInt(bThis.attr('data-numbox-max'));//设置最大值
		var binput=parseInt(bThis.find("input").val());//当前数量
		if($(this).text()=='+'){ 
//			binput++
			bThis.find("input").val(binput>bmax?bmax:binput);
			//获取数量变化时合计的价格
			var price = $('.orderprice').text();
			var totalPrice = parseFloat(price)+2;
			$('.orderprice').text(totalPrice.toFixed(2));
		}else{
//			binput--
			bThis.find("input").val((binput<bmin)?bmin:binput);
			//获取数量变化时合计的价格
			if (binput > -1) {
				var price = $('.orderprice').text();
				var totalPrice = parseFloat(price)-2;
				$('.orderprice').text(totalPrice.toFixed(2));
			}
		}
	})
}
// 检测是否安装支付服务
function checkServices(pc){
	if(!pc.serviceReady){
		var txt=null;
		switch(pc.id){
			case "alipay":
			txt="检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？";
			break;
			default:
			txt="系统未安装“"+pc.description+"”服务，无法完成支付，是否立即安装？";
			break;
		}
		plus.nativeUI.confirm(txt,function(e){
			if(e.index==0){
				pc.installService();
			}
		},pc.description);
	}
}
